
import axios from 'axios'

import {Toast,Notify} from 'vant'


function showLoading(){
    Toast.clear();
    Toast.loading({
        message: '加载中',
        forbidClick: true,
        loadingType: 'spinner'
    })
}

function showFail(msg){
    msg = msg || '未知错误'
    Notify({type:'danger',message:msg,duration:1000})
}

//拦截器   Interceptors

const baseURL = "http://8.136.10.30:5237";
axios.defaults.baseURL = baseURL;
// axios.defaults.headers.common['Authorization'] = 'WH2008';
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';



// Add a request interceptor  请求发送之前
axios.interceptors.request.use(function(config){
    //成功
    showLoading()
    
    config.headers['token'] = localStorage.getItem('token')
    // console.log(config);
    return config
} , function(error){
    //失败
    showFail('网络异常')
    return Promise.reject(error)
})

// Add a response interceptor   响应数据结束
axios.interceptors.response.use(function (response) {
    // 成功
    Toast.clear();   
    console.log(response.data)
    if(response.data.code==402 || response.data.code==500){
        // error 
        Notify({
            message: response.data.msg || '数据异常',
            color: '#ad0000',
            background: '#ffe1e1',
        });
    }

    if(response.data.code==3000 ){
        // error 
        Notify({
            message: response.data.msg ,
            color: '#ad0000',
            background: '#ffe1e1',
        });
        // 登录失效 
        // router.push({name:'login'})
    }
    return response;
  }, function (error) {
    // 失败 
    showFail('服务器异常')
    return Promise.reject(error);
});




// GET请求

export const get = function(url,params,headers){
    return new Promise(function(resolve,reject){
        axios.get(url,{
            params,
            headers
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

// POST请求

export const post =  function(url,body,headers){
    return new Promise(function(resolve,reject){
        axios.post(url,body,{    //axios里 post也有 params参数
            
            headers
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}



export {axios,baseURL}